# include "jam.h"
# include "newstr.h"
# include "hash.h"
#include "alloc.h"

static ALLOC *stralloc = 0;
typedef const char *STRING;
static struct hash *strhash = 0;
static int strtotal = 0;

const char * newstr( const char *string ) {
  STRING str, *s = &str;
  if( !strhash ) {
    strhash = hashinit( sizeof( STRING ), "strings" );
  }
  *s = string;
  if( hashenter( strhash, ( HASHDATA ** )&s ) ) {
    int l = strlen( string );
    if( !stralloc ) {
      stralloc = alloc2_init( 4096 );
    }
    char *m = alloc2_enter( stralloc, l + 1 );
    if( DEBUG_MEM ) {
      printf( "newstr: allocating %d bytes\n", l + 1 );
    }
    strtotal += l + 1;
    memcpy( m, string, l + 1 );
    *s = m;
  }
  return *s;
}

const char * copystr( const char *s ) {
  return s;
}

void freestr( const char * s ) {
  ( void )s;
}

void donestr() {
  hashdone( strhash );
  strhash = 0;
  strtotal = 0;
  alloc_free( stralloc );
  stralloc = 0;
  if( DEBUG_MEM ) {
    printf( "%dK in strings\n", strtotal / 1024 );
  }
}
